package com.fenghongzhang.day013;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements OneFragment.MyListener {
    private ViewPager vp;
    private List<Fragment> list;

    private ThreeFragment threeFragment;
    private  int index = 0;

    private  Timer timer;
    private Handler handler = new Handler(){
        //ctrl + o
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 110){
                vp.setCurrentItem(index++);
                if(index >= list.size()){
                    timer.cancel();
                }
            }


        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        vp = (ViewPager) findViewById(R.id.vp);

         list = new ArrayList<>();
        list.add(new OneFragment());
        list.add(new TwoFragment());
         threeFragment = new ThreeFragment();
        list.add(threeFragment);

        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), list);
        vp.setAdapter(fragmentAdapter);

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(110);
            }
        },0,1000);

        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                if(position == list.size()-1){
                    //最后一页的时候,才开始倒计时.
                    threeFragment.handler.sendEmptyMessage(250);
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }


    @Override
    public void sendInt(int i) {
        vp.setCurrentItem(i);
    }
}
